clear all
set matsize 11000
set maxvar 11000

cap ssc install reghdfe
cap ssc install eststo
cap ssc install distinct

********************************************************************************
*          TABLE I: BASELINE EFFECT OF CEO'S TRUST ON FIRM'S PATENTS           *
********************************************************************************
cap log close
log using "Table I_Baseline effects.log", replace

//PREPARE DATA
* set globals
global firm = "firmage firmage2"
global ceo = "gender age age2 yrinco i.education"
global country = "logGDP logpop GDPgr lsc gov3_pcr logustradevol logcallpat"
global culture = "highincome_sd getahead_sd risktakinggps_sd patiencegps_sd"
global sample = "year < 2012 & !nonUS"
global cluster = "mainethcode"


//PREPARE TABLE
eststo clear
use "Baseline CEO firm year sample.dta", clear
eststo col1: /// baseline
	reghdfe ash_f1allpat trust_sd ${firm} ${ceo} if ${sample}, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local spec               "Baseline"
		estadd local baselineFE         "X"
		estadd local controls           "X"
		distinct boardid if e(sample)
		eststo col1, add(nofirms r(ndistinct))
	sum f1allpat if e(sample)
	dis _b[trust_sd] * r(mean)
eststo col2: /// additional SIC3 x year fixed effects
	reghdfe ash_f1allpat trust_sd ${firm} ${ceo} if ${sample}, ///
	a(boardid sic3#year) cluster(${cluster}) keepsin
		estadd local spec               "Ind trends"
		estadd local baselineFE         "X"
		estadd local controls           "X"
		estadd local additionalFE       "X"
		distinct boardid if e(sample)
		eststo col2, add(nofirms r(ndistinct))
eststo col3: /// forward citation-weighted
	reghdfe ash_f1allpat_citff trust_sd ${firm} ${ceo} if ${sample}, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local spec               "Fwd cites"
		estadd local baselineFE         "X"
		estadd local controls           "X"
		distinct boardid if e(sample)
		eststo col3, add(nofirms r(ndistinct))
eststo col4: /// (granted) patent value-weighted
	reghdfe ash_f1uspat_xi trust_sd ${firm} ${ceo} if ${sample} & year < 2008, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local spec               "Pat value"
		estadd local baselineFE         "X"
		estadd local controls           "X"
		distinct boardid if e(sample)
		eststo col4, add(nofirms r(ndistinct))

use "CEO transition event sample.dta", clear
gen postxdeltatrust = postchange * deltatrust if trust_sd != .
gen postxtrustbf = postchange * trustbf if trust_sd != .
global exoeventsample = "!bothnonUS & (retire5yr | deathwi1yr)"

eststo col5: /// retirement and death events OLS
	reghdfe ash_f1allpat trust_sd ${firm} ${ceo} ///
	if ${exoeventsample}, a(eventid year) cluster(${cluster}) keepsin
		estadd local spec               "Retd/died"
		estadd local baselineFE         "X"
		estadd local controls           "X"
		distinct boardid if e(sample)
		eststo col5, add(nofirms r(ndistinct))
eststo col6: /// retirement and death events IV
	ivreghdfe ash_f1allpat (postxdeltatrust = postxtrustbf) postchange ${firm} ${ceo} ///
	if ${exoeventsample}, a(eventid year) cluster(mainethcoder) keepsin
		estadd local spec               "Retd/died IV"
		estadd local baselineFE         "X"
		estadd local controls           "X"
		distinct boardid if e(sample)
		eststo col6, add(nofirms r(ndistinct))

use "Baseline CEO firm year sample.dta", clear
eststo col7: /// country of origin controls
	reghdfe ash_f1allpat trust_sd ${firm} ${ceo} ${country} if ${sample}, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local spec               "Country ctrls"
		estadd local baselineFE         "X"
		estadd local controls           "X"
		estadd local countrycontrols    "X"
		distinct boardid if e(sample)
		eststo col7, add(nofirms r(ndistinct))
eststo col8: /// other cultural trait controls
	reghdfe ash_f1allpat trust_sd ${firm} ${ceo} ${culture} if ${sample}, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local spec               "Other traits"
		estadd local baselineFE         "X"
		estadd local controls           "X"
		estadd local culturalcontrols   "X"
		distinct boardid if e(sample)
		eststo col8, add(nofirms r(ndistinct))

esttab /*using "Table I_Baseline effects.tex"*/, ///
	cells(b(star fmt(3)) se(par fmt(3))) starlevels(* 0.1 ** 0.05 *** 0.01) ///
	nomtitle collabels(none) label varwidth(29) modelwidth(12) ///
	mgroups("arsinh(Future patent applications)", pattern(1 0 0 0 0 0 0 0) ///
		prefix(\multicolumn{@span}{c}{) suffix(}) span) ///
	keep(trust_sd postxdeltatrust) order(trust_sd postxdeltatrust) ///
	coeflab(trust_sd "CEO's trust" postxdeltatrust "Post $\times$ Change in trust") ///
	stats(spec baselineFE controls additionalFE countrycontrols culturalcontrols N nofirms, ///
		fmt(%9.0fc %9.0fc) ///
		lab("Specification" "Firm \& Year FEs" "Baseline controls" "Industry $\times$ Year FEs" ///
			"Home country controls" "Other cultural traits" "Observations" "Firms"))

cap log close

********************************************************************************
*        TABLE II: CEO'S TRUST EFFECT BY INDUSTRY AND CEO'S BACKGROUND         *
********************************************************************************
cap log close
log using "Table II_Effect by industry and background.log", replace

//PREPARE DATA
use "Baseline CEO firm year sample.dta", clear
* construct additional variables
gen pharmachem = inlist(sector, ///
	"Chemicals", ///
	"Pharmaceuticals and Biotechnology", ///
	"Health")
gen electroit = inlist(sector, ///
	"Electronic & Electrical Equipment", ///
	"Information Technology Hardware", ///
	"Software & Computer Services")
gen timesinceCEO = min(year - termstartyr, 9)
gen postgradnonMBA = (education == 3 & MBA == 0) | education == 4
gen hasRDexp = preCEO_resdir == 1 | preCEO_techdir == 1 
* set globals
global firm = "firmage firmage2"
global ceo = "gender age age2 yrinco i.education"
global sample = "year < 2012 & !nonUS"
global cluster = "mainethcode"


//PREPARE TABLE
eststo clear
eststo col1: /// pharma/chemical industries
	reghdfe ash_f1allpat trust_sd ${firm} ${ceo} ///
	if ${sample} & pharmachem, a(boardid year) cluster(${cluster}) keepsin
		estadd local sample     "Pharma/chem"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col1, add(nofirms r(ndistinct))
eststo col2: /// pharma/chemical industries, by tenure as CEO
	reghdfe ash_f1allpat c.trust_sd##c.timesinceCEO ${firm} ${ceo} ///
	if ${sample} & pharmachem, a(boardid year) cluster(${cluster}) keepsin
		estadd local sample     "Pharma/chem"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col2, add(nofirms r(ndistinct))
eststo col3: /// ICT/electronic industries
	reghdfe ash_f1allpat trust_sd ${firm} ${ceo} ///
	if ${sample} & electroit, a(boardid year) cluster(${cluster}) keepsin
		estadd local sample     "ICT/elec"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col3, add(nofirms r(ndistinct))
eststo col4: /// ICT/electronic industries, by tenure as CEO
	reghdfe ash_f1allpat c.trust_sd##c.timesinceCEO ${firm} ${ceo} ///
	if ${sample} & electroit, a(boardid year) cluster(${cluster}) keepsin
		estadd local sample     "ICT/elec"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col4, add(nofirms r(ndistinct))
eststo col5: /// other industries
	reghdfe ash_f1allpat trust_sd ${firm} ${ceo} ///
	if ${sample} & !pharmachem & !electroit, a(boardid year) cluster(${cluster}) keepsin
		estadd local sample     "Others"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col5, add(nofirms r(ndistinct))
eststo col6: /// by CEO's education	
	reghdfe ash_f1allpat c.trust_sd#i.postgradnonMBA postgradnonMBA ${firm} ${ceo} ///
	if ${sample}, a(boardid year) cluster(${cluster}) keepsin
		estadd local sample     "Full"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col6, add(nofirms r(ndistinct))
eststo col7: /// by CEO's experience	
	reghdfe ash_f1allpat c.trust_sd#i.hasRDexp hasRDexp ${firm} ${ceo} ///
	if ${sample}, a(boardid year) cluster(${cluster}) keepsin
		estadd local sample     "Full"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col7, add(nofirms r(ndistinct))

global coeflist1 = "trust_sd c.trust_sd#c.timesinceCEO"
global coeflist2 = "0.postgradnonMBA#c.trust_sd 1.postgradnonMBA#c.trust_sd"
global coeflist3 = "0.hasRDexp#c.trust_sd 1.hasRDexp#c.trust_sd"
esttab /*using "Table II_Effect by industry and background.tex"*/, ///
	cells(b(star fmt(3)) se(par fmt(3))) starlevels(* 0.1 ** 0.05 *** 0.01) ///
	nomtitle collabels(none) label varwidth(32) modelwidth(12) ///
	mgroups("arsinh(Future patent applications)", pattern(1 0 0 0 0 0 0) ///
		prefix(\multicolumn{@span}{c}{) suffix(}) span) ///
	keep(${coeflist1} ${coeflist2} ${coeflist3}) order(${coeflist1} ${coeflist2} ${coeflist3}) ///
	coeflab(trust_sd "CEO's trust" ///
			c.trust_sd#c.timesinceCEO "Trust $\times$ Tenure as CEO" ///
			0.postgradnonMBA#c.trust_sd "Trust $\times$ MBA/no grad deg" ///
			1.postgradnonMBA#c.trust_sd "Trust $\times$ Non-MBA grad deg" ///
			0.hasRDexp#c.trust_sd "Trust $\times$ No prior R\&D exp" ///
			1.hasRDexp#c.trust_sd "Trust $\times$ Prior R\&D exp") ///
	stats(sample FE controls N nofirms, fmt(%9.0fc %9.0fc) ///
		lab("Sample" "Firm \& Year FEs" "Baseline controls" "Observations" "Firms"))

cap log close

********************************************************************************
*          TABLE III: CEO'S TRUST EFFECT ON QUALITY-WEIGHTED PATENTS           *
********************************************************************************
cap log close
log using "Table III_Effect on quality-weighted patents.log", replace

//PREPARE DATA
use "Baseline CEO firm year sample.dta", clear
* construct additional variables
gen share_f1allpat_new_topq10 = f1allpat_new_topq10/f1allpat
replace share_f1allpat_new_topq10 = 0 if share_f1allpat_new_topq10 == .
gen ash_f1avgcitff = asinh(f1allpat_citff/f1allpat)
replace ash_f1avgcitff = 0 if ash_f1avgcitff == .
gen ash_f1avgxi = asinh(f1uspat_xi/f1uspat) if year < 2008
replace ash_f1avgxi = 0 if f1uspat == 0 & year < 2008
* set globals
global firm = "firmage firmage2"
global ceo = "gender age age2 yrinco i.education"
global sample = "year < 2012 & !nonUS"
global cluster = "mainethcode"


//PREPARE TABLE
eststo clear
eststo col1: /// explorative patents
	reghdfe ash_f1allpat_new_topq10 trust_sd ${firm} ${ceo} if ${sample}, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col1, add(nofirms r(ndistinct))
eststo col2: /// disruptive patents
	reghdfe ash_f1allpat_posCD trust_sd ${firm} ${ceo} if ${sample}, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col2, add(nofirms r(ndistinct))
eststo col3: /// top-decile-importance patents
	reghdfe ash_f1uspat_sig_topq10 trust_sd ${firm} ${ceo} if ${sample}, ///
	a(boardid year) cluster(${cluster}) keepsin	
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col3, add(nofirms r(ndistinct))
eststo col4: /// backward NPL citation-weighted
	reghdfe ash_f1allpat_npl trust_sd ${firm} ${ceo} if ${sample}, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col4, add(nofirms r(ndistinct))
eststo col5: /// technological scope-weighted
	reghdfe ash_f1allpat_sco trust_sd ${firm} ${ceo} if ${sample}, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col5, add(nofirms r(ndistinct))
eststo col6: /// explorative patent share 	
	reghdfe share_f1allpat_new_topq10 trust_sd ${firm} ${ceo} if ${sample}, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col6, add(nofirms r(ndistinct))
eststo col7: /// average forward citations 	
	reghdfe ash_f1avgcitff trust_sd ${firm} ${ceo} if ${sample}, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col7, add(nofirms r(ndistinct))
eststo col8: /// average patent value	
	reghdfe ash_f1avgxi trust_sd ${firm} ${ceo} if ${sample} & year < 2008, ///
	a(boardid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col8, add(nofirms r(ndistinct))

lab var ash_f1allpat_new_topq10     "Explorative pat"
lab var ash_f1allpat_posCD          "Disruptive pat"
lab var ash_f1uspat_sig_topq10      "Patent importance"
lab var ash_f1allpat_npl            "Backward NPL cites"
lab var ash_f1allpat_sco            "Tech scope"
lab var share_f1allpat_new_topq10   "(Explor pat)"
lab var ash_f1avgcitff              "(Avg cites)"
lab var ash_f1avgxi                 "(Avg value)"
esttab /*using "Table III_Effect on quality-weighted patents.tex"*/, ///
	cells(b(star fmt(3)) se(par fmt(3))) starlevels(* 0.1 ** 0.05 *** 0.01) ///
	collabels(none) label varwidth(18) modelwidth(15) ///
	mgroups("arsinh(Future quality-weighted patents)" "Share" "arsinh" "arsinh", ///
		pattern(1 0 0 0 0 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span) ///
	keep(trust_sd) coeflab(trust_sd "CEO's trust") ///
	stats(FE controls N nofirms, fmt(%9.0fc %9.0fc) ///
		lab("Firm \& Year FEs" "Baseline controls" "Observations" "Firms"))

cap log close

********************************************************************************
*              TABLE IV: CEO'S TRUST AND CORPORATE TRUST CULTURE               *
*              TABLE A15: CEO'S TRUST AND CORPORATE TRUST CULTURE              *
********************************************************************************
cap log close
log using "Tables IV A15_Corporate trust culture.log", replace

//PREPARE DATA
use "Employee review trust sentiment sample.dta", clear
* construct time period variables
cap drop timesinceCEO* timeperiod
gen timesinceCEO = min(year - termstartyr, 9)
gen timesinceCEO2 = timesinceCEO^2
gen timesinceCEO3 = timesinceCEO^3
gen timeperiod = 1 if inrange(timesinceCEO, 0, 2)
replace timeperiod = 2 if inrange(timesinceCEO, 3, 4)
replace timeperiod = 3 if inrange(timesinceCEO, 5, 6)
replace timeperiod = 4 if inrange(timesinceCEO, 7, 8)
replace timeperiod = 5 if timesinceCEO >= 9
* compute corporate trust culture measures
cap drop trustsentiment
gen trustsentiment = (trustsentiment_pos == 1) - (trustsentiment_neg == 1)
cap drop trust_mtoe trust_etom
gen trustsentiment_mtoe = ///
	(trustsentiment_pos == 1) * (trustdirection_mtoe == 1) ///
	- (trustsentiment_neg == 1) * (trustdirection_mtoe == 1)
gen trustsentiment_etom = ///
	(trustsentiment_pos == 1) * (trustdirection_etom == 1) ///
	- (trustsentiment_neg == 1) * (trustdirection_etom == 1) 
foreach var in trustsentiment trustsentiment_mtoe trustsentiment_etom {
	replace `var' = . if trustsentiment_pos == .
}
gen trustsentiment_mtoe_pos = (trustsentiment_pos == 1) * (trustdirection_mtoe == 1)
gen trustsentiment_mtoe_neg = (trustsentiment_neg == 1) * (trustdirection_mtoe == 1)
gen trustsentiment_etom_pos = (trustsentiment_pos == 1) * (trustdirection_etom == 1)
gen trustsentiment_etom_neg = (trustsentiment_neg == 1) * (trustdirection_etom == 1)
gen trustsentiment_abs = trustsentiment_pos | trustsentiment_neg
gen trustsentiment_mtoe_abs = trustsentiment_mtoe_pos | trustsentiment_mtoe_neg
gen trustsentiment_etom_abs = trustsentiment_etom_pos | trustsentiment_etom_neg
foreach var in trustsentiment trustsentiment_mtoe trustsentiment_etom {
	replace `var' = `var' * 100
	replace `var'_pos = `var'_pos * 100
	replace `var'_neg = `var'_neg * 100
	replace `var'_abs = `var'_abs * 100
}
* compute review counts
foreach var in trustsentiment approveceo iscurrentjob reviewgap firmage ///
	trust_sd gender age yrinco education !nonUS ///
	highincome_sd getahead_sd risktakinggps_sd patiencegps_sd {
	keep if `var' != .
}
*** all reviews
cap drop *_all
bysort boardid ceoid termstartyr: gen revcnt_all = _N
bysort boardid ceoid termstartyr: egen revcnt_allcur = sum(iscurrentjob)
gen w_all = 1/revcnt_all
gen w_allcur = 1/revcnt_allcur
*** R&D workers only
replace jobtitle = upper(jobtitle)
cap drop RDworker *_rd
gen RDworker = ///
	strpos(jobtitle, "ENGINEER") ///
	| strpos(jobtitle, "SCIEN") /// 
	| strpos(jobtitle, "RESEARCH") ///
	| strpos(jobtitle, "TECHNOLOGY DEVELOP") ///
	| strpos(jobtitle, "R&D") ///
	| strpos(jobtitle, "R& D") ///
	| strpos(jobtitle, "R &D") ///
	| strpos(jobtitle, "R & D") ///
	| strpos(jobtitle, "RDD ") 
bysort boardid ceoid termstartyr: egen revcnt_rd = sum(RDworker == 1)
bysort boardid ceoid termstartyr: egen revcnt_rdcur = sum(RDworker == 1 & iscurrentjob)
gen w_rd = 1/revcnt_rd
gen w_rdcur = 1/revcnt_rdcur
* set globals
global review = "approveceo iscurrentjob reviewgap"
global firm = "firmage firmage2"
global ceo = "gender age age2 yrinco i.education nonUS"
global culture = "highincome_sd getahead_sd risktakinggps_sd patiencegps_sd"
global reviewsample = "revcnt_all > 49"
global rdreviewsample = "RDworker & revcnt_rd > 24 & revcnt_all > 49"


//PREPARE TABLE
foreach table in "IV" "A15" {
	if "`table'" == "IV" {
		global cluster = "mainethcode"
	}
	if "`table'" == "A15" {
		global cluster = "ceoid"
	}
	
	eststo clear
	eststo col1: /// both directions of trust with industry FEs
		reghdfe trustsentiment trust_sd ${review} ${firm} ${ceo} ${culture} ///
		if ${reviewsample} [aw = w_all], a(sic3 reviewyear) cluster(${cluster}) keepsin
			sum trustsentiment_pos [aw = w_all] if e(sample)
			estadd scalar mean_pos r(mean)
			sum trustsentiment_neg [aw = w_all] if e(sample)
			estadd scalar mean_neg r(mean)
			sum trustsentiment_abs [aw = w_all] if e(sample)
			estadd scalar mean_abs r(mean)
			estadd scalar ratio _b[trust_sd]/r(mean)
			estadd local direction      "Both"
			estadd local sample         "All"
			estadd local controls       "X"
			estadd local industryFE     "X"
			distinct boardid if e(sample)
			eststo col1, addscalars(nofirms r(ndistinct))
	eststo col2: /// both directions of trust with firm FEs
		reghdfe trustsentiment trust_sd ${review} ${firm} ${ceo} ${culture} ///
		if ${reviewsample} [aw = w_all], a(boardid reviewyear) cluster(${cluster}) keepsin
			sum trustsentiment_pos [aw = w_all] if e(sample)
			estadd scalar mean_pos r(mean)
			sum trustsentiment_neg [aw = w_all] if e(sample)
			estadd scalar mean_neg r(mean)
			sum trustsentiment_abs [aw = w_all] if e(sample)
			estadd scalar mean_abs r(mean)
			estadd scalar ratio _b[trust_sd]/r(mean)
			estadd local direction      "Both"
			estadd local sample         "All"
			estadd local controls       "X"
			estadd local baselineFE     "X"
			distinct boardid if e(sample)
			eststo col2, addscalars(nofirms r(ndistinct))
	eststo col3: /// top down trust
		reghdfe trustsentiment_mtoe trust_sd ${review} ${firm} ${ceo} ${culture} ///
		if ${reviewsample} [aw = w_all], a(boardid reviewyear) cluster(${cluster}) keepsin
			sum trustsentiment_mtoe_pos [aw = w_all] if e(sample)
			estadd scalar mean_pos r(mean)
			sum trustsentiment_mtoe_neg [aw = w_all] if e(sample)
			estadd scalar mean_neg r(mean)
			sum trustsentiment_mtoe_abs [aw = w_all] if e(sample)
			estadd scalar mean_abs r(mean)
			estadd scalar ratio _b[trust_sd]/r(mean)
			estadd local direction      "Top down"
			estadd local sample         "All"
			estadd local controls       "X"
			estadd local baselineFE     "X"
			distinct boardid if e(sample)
			eststo col3, addscalars(nofirms r(ndistinct))
	eststo col4: /// bottom up trust
		reghdfe trustsentiment_etom trust_sd ${review} ${firm} ${ceo} ${culture} ///
		if ${reviewsample} [aw = w_all], a(boardid reviewyear) cluster(${cluster}) keepsin
			sum trustsentiment_etom_pos [aw = w_all] if e(sample)
			estadd scalar mean_pos r(mean)
			sum trustsentiment_etom_neg [aw = w_all] if e(sample)
			estadd scalar mean_neg r(mean)
			sum trustsentiment_etom_abs [aw = w_all] if e(sample)
			estadd scalar mean_abs r(mean)
			estadd scalar ratio _b[trust_sd]/r(mean)
			estadd local direction      "Bottom up"
			estadd local sample         "All"
			estadd local controls       "X"
			estadd local baselineFE     "X"
			distinct boardid if e(sample)
			eststo col4, addscalars(nofirms r(ndistinct))
	eststo col5: /// top down trust among R&D workers
		reghdfe trustsentiment_mtoe trust_sd ${review} ${firm} ${ceo} ${culture} ///
		if ${rdreviewsample} [aw = w_rd], a(boardid reviewyear) cluster(${cluster}) keepsin
			sum trustsentiment_mtoe_pos [aw = w_rd] if e(sample)
			estadd scalar mean_pos r(mean)
			sum trustsentiment_mtoe_neg [aw = w_rd]if e(sample)
			estadd scalar mean_neg r(mean)
			sum trustsentiment_mtoe_abs [aw = w_rd] if e(sample)
			estadd scalar mean_abs r(mean)
			estadd scalar ratio _b[trust_sd]/r(mean)
			estadd local direction      "Top down"
			estadd local sample         "R\&D workers"
			estadd local controls       "X"
			estadd local baselineFE     "X"
			distinct boardid if e(sample)
			eststo col5, addscalars(nofirms r(ndistinct))
	eststo col6: /// top down trust by tenure as CEO
		reghdfe trustsentiment_mtoe c.trust_sd#i.timeperiod timesinceCEO* ${review} ${firm} ${ceo} ${culture} ///
		if ${reviewsample} [aw = w_all], a(boardid reviewyear) cluster(${cluster}) keepsin
			sum trustsentiment_mtoe_pos [aw = w_all] if e(sample)
			estadd scalar mean_pos r(mean)
			sum trustsentiment_mtoe_neg [aw = w_all] if e(sample)
			estadd scalar mean_neg r(mean)
			sum trustsentiment_mtoe_abs [aw = w_all] if e(sample)
			estadd scalar mean_abs r(mean)
			estadd local direction      "Top down"
			estadd local sample         "All"
			estadd local controls       "X"
			estadd local baselineFE     "X"
			distinct boardid if e(sample)
			eststo col6, addscalars(nofirms r(ndistinct))
	eststo col7: /// top down trust among R&D workers by tenure as CEO
		reghdfe trustsentiment_mtoe c.trust_sd#i.timeperiod timesinceCEO* ${review} ${firm} ${ceo} ${culture} ///
		if ${rdreviewsample} [aw = w_rd], a(boardid reviewyear) cluster(${cluster}) keepsin
			sum trustsentiment_mtoe_pos [aw = w_rd] if e(sample)
			estadd scalar mean_pos r(mean)
			sum trustsentiment_mtoe_neg [aw = w_rd] if e(sample)
			estadd scalar mean_neg r(mean)
			sum trustsentiment_mtoe_abs [aw = w_rd] if e(sample)
			estadd scalar mean_abs r(mean)
			estadd local direction      "Top down"
			estadd local sample         "R\&D workers"
			estadd local controls       "X"
			estadd local baselineFE     "X"
			distinct boardid if e(sample)
			eststo col7, addscalars(nofirms r(ndistinct))
	
	global coeflist = "1.timeperiod#c.trust_sd 2.timeperiod#c.trust_sd 3.timeperiod#c.trust_sd 4.timeperiod#c.trust_sd 5.timeperiod#c.trust_sd"
	esttab /*using "Table `table'_Corporate trust culture.tex"*/, ///	
		cells(b(star fmt(3)) se(par fmt(3))) starlevels(* 0.1 ** 0.05 *** 0.01) ///
		nomtitle collabels(none) label varwidth(40) modelwidth(12) ///
		mgroups("Employee review's trust sentiment", pattern(1 0 0 0 0 0 0 0) ///
			prefix(\multicolumn{@span}{c}{) suffix(}) span) ///
		keep(trust_sd ${coeflist}) order(trust_sd ${coeflist}) ///
		coeflab(trust_sd "CEO's trust" ///
				1.timeperiod#c.trust_sd "Trust $\times$ 1(Tenure as CEO <= 2)" ///)
				2.timeperiod#c.trust_sd "Trust $\times$ 1(Tenure as CEO in [3,4])" ///
				3.timeperiod#c.trust_sd "Trust $\times$ 1(Tenure as CEO in [5,6])" ///
				4.timeperiod#c.trust_sd "Trust $\times$ 1(Tenure as CEO in [7,9])" ///
				5.timeperiod#c.trust_sd "Trust $\times$ 1(Tenure as CEO >= 9)") ///
		stats(mean_pos mean_neg ratio direction sample controls industryFE baselineFE N nofirms, ///
			fmt(%9.3fc %9.3fc %9.3fc %9.0fc %9.0fc) ///
			lab("Positive reviews" "Negative reviews" "Normalized effect size" "Trust direction" "Sample" ///
				"Baseline controls" "Industry \& Review year FEs" "Firm \& Review year FEs" "Observations" "Firms"))
}

cap log close

********************************************************************************
*                 TABLE V: CEO'S TRUST AND DIRECTOR SELECTION                  *
********************************************************************************
cap log close
log using "Table V_Director selection.log", replace

//PREPARE DATA
use "Director CEO firm year sample.dta", clear
* construct director type indicators
cap drop *dir
gen newdir = year == DIR_firstyear_key & year != DIR_lastyear_key & year != termendyr
gen leftdir = year == DIR_lastyear_key & year != termendyr & DIR_age < 75 //90th percentile in age at leaving board
gen remdir = DIR_firstyear_key < termstartyr & DIR_lastyear_key >= termendyr
bysort boardid ceoid termno directorid: egen NEWdir = max(newdir)
bysort boardid ceoid termno directorid: egen LEFTdir = max(leftdir)
bysort boardid ceoid termno directorid: egen REMdir = min(remdir)
* compute average trust by director type
cap drop *dirtrust
bysort boardid ceoid year: egen tempnew = mean(DIR_trust) if newdir
bysort boardid ceoid year: egen newdirtrust = mean(tempnew)
bysort boardid ceoid year: egen tempstay = mean(DIR_trust) if newdir & !LEFTdir
bysort boardid ceoid year: egen staydirtrust = mean(tempstay)
bysort boardid ceoid year: egen templeft = mean(DIR_trust) if leftdir
bysort boardid ceoid year: egen leftdirtrust = mean(templeft)
bysort boardid ceoid year: egen tempmean = mean(DIR_trust)
bysort boardid ceoid year: egen meandirtrust = mean(tempmean)
drop temp*
* compute director counts
bysort boardid ceoid year: egen countnew = sum(newdir)
bysort boardid ceoid year: egen countstay = sum(newdir & !LEFTdir)
bysort boardid ceoid year: egen countleft = sum(leftdir)
bysort boardid ceoid year: gen count = _N
* set globals
global firm = "firmage firmage2"
global ceo = "gender age age2 yrinco i.education"
global sample = "year < 2012 & !nonUS & baselinesample"
global cluster = "mainethcode"


//PREPARE TABLE
eststo clear
* observation unit: directorid x boardid x ceoid x year
eststo col1: /// new directors
	reghdfe DIR_trust trust ${firm} ${ceo} if ${sample} & newdir, ///
		a(boardid year) cluster(${cluster}) keepsin
		estadd local sample 	"New"
		estadd local obsunit	"D-F-Y-CEO"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col1, add(nofirms r(ndistinct))
eststo col2: /// staying directors
	reghdfe DIR_trust trust ${firm} ${ceo} if ${sample} & newdir & !LEFTdir, ///
		a(boardid year) cluster(${cluster}) keepsin
		estadd local sample 	"Staying"
		estadd local obsunit	"D-F-Y-CEO"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col2, add(nofirms r(ndistinct))
eststo col3: /// leaving directors
	reghdfe DIR_trust trust ${firm} ${ceo} if ${sample} & leftdir, ///
		a(boardid year) cluster(${cluster}) keepsin
		estadd local sample 	"Leaving"
		estadd local obsunit	"D-F-Y-CEO"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col3, add(nofirms r(ndistinct))
* observation unit: boardid x ceoid x year
egen tagbrdceoyr = tag(boardid ceoid year)
eststo col4: /// new directors
	reghdfe newdirtrust trust ${firm} ${ceo} if ${sample} & tagbrdceoyr, ///
		a(boardid year) cluster(${cluster}) keepsin
		estadd local sample 	"New"
		estadd local obsunit	"F-Y-CEO"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col4, add(nofirms r(ndistinct))
eststo col5: /// staying directors
	reghdfe staydirtrust trust ${firm} ${ceo} if ${sample} & tagbrdceoyr, ///
		a(boardid year) cluster(${cluster}) keepsin
		estadd local sample 	"Staying"
		estadd local obsunit	"F-Y-CEO"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col5, add(nofirms r(ndistinct))
eststo col6: /// leaving directors
	reghdfe leftdirtrust trust ${firm} ${ceo} if ${sample} & tagbrdceoyr, ///
		a(boardid year) cluster(${cluster}) keepsin
		estadd local sample 	"Leaving"
		estadd local obsunit	"F-Y-CEO"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col6, add(nofirms r(ndistinct))
eststo col7: /// all directors
	reghdfe meandirtrust trust ${firm} ${ceo} if ${sample} & tagbrdceoyr, ///
		a(boardid year) cluster(${cluster}) keepsin
		estadd local sample 	"All"
		estadd local obsunit	"F-Y-CEO"
		estadd local FE         "X"
		estadd local controls   "X"
		distinct boardid if e(sample)
		eststo col7, add(nofirms r(ndistinct))

esttab /*using "Table V_Director selection.tex"*/, ///
	cells(b(star fmt(3)) se(par fmt(3))) starlevels(* 0.1 ** 0.05 *** 0.01) ///
	nomtitle collabels(none) label varwidth(18) modelwidth(12)  ///
	mgroups("Individual director's trust" "Average director's trust", pattern(1 0 0 1 0 0 0) ///
		prefix(\multicolumn{@span}{c}{) suffix(}) span) ///
	keep(trust) coeflab(trust "CEO's trust") ///
	stats(sample obsunit FE controls N nofirms, fmt(%9.0fc %9.0fc) ///
		lab("Director sample" "Observation unit" "Firm \& Year FEs" "Baseline controls" "Observations" "Firms"))

cap log close

********************************************************************************
*    TABLE VI: CEO'S TRUST EFFECT BY PRE-TRANSITION RESEARCHER POOL QUALITY    *
********************************************************************************
cap log close
log using "Table VI_Effect by pre-transition researcher-pool quality.log", replace

//PREPARE DATA
use "CEO transition event sample.dta", clear
* construct additional variables
gen f1allpat_highq = 0
forval i = 6/10 {
	replace f1allpat_highq = f1allpat_highq + f1allpat_citff_dec`i'
}
gen ash_f1allpat_highq = asinh(f1allpat_highq)
gen ash_efficiency = asinh(f1allpat/xrd)
replace ash_efficiency = asinh(f1allpat) if xrd == 0
* set globals
global firm = "firmage firmage2 ash_xrd"
global ceo = "gender age age2 yrinco i.education"
global eventsample = "!bothnonUS"
global cluster = "mainethcode"


//PREPARE TABLE
eststo clear
eststo col1: /// all patents
	reghdfe ash_f1allpat c.trust_sd##c.resqual ${firm} ${ceo} if ${eventsample}, ///
	a(eventid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct eventid if e(sample)
		eststo col1, add(noevents r(ndistinct))
eststo col2: /// top-quality patents
	reghdfe ash_f1allpat_highq c.trust_sd##c.resqual ${firm} ${ceo} if ${eventsample}, ///
	a(eventid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct eventid if e(sample)
		eststo col2, add(noevents r(ndistinct))
eststo col3: /// R&D efficiency
	reghdfe ash_efficiency c.trust_sd##c.resqual ${firm} ${ceo} if ${eventsample}, ///
	a(eventid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct eventid if e(sample)
		eststo col3, add(noevents r(ndistinct))
eststo col4: /// all patents
	reghdfe ash_f1allpat c.trust_sd#i.resqualpct ${firm} ${ceo} if ${eventsample}, ///
	a(eventid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct eventid if e(sample)
		eststo col4, add(noevents r(ndistinct))
eststo col5: /// future sales
	reghdfe f2logsale c.trust_sd##c.resqual ${firm} ${ceo} if ${eventsample}, ///
	a(eventid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct eventid if e(sample)
		eststo col5, add(noevents r(ndistinct))	
eststo col6: /// future employment	
	reghdfe f2logemp c.trust_sd##c.resqual ${firm} ${ceo} if ${eventsample}, ///
	a(eventid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct eventid if e(sample)
		eststo col6, add(noevents r(ndistinct))	
eststo col7: /// future TFP
	reghdfe f2TFP_KL c.trust_sd##c.resqual ${firm} ${ceo} if ${eventsample}, ///
	a(eventid year) cluster(${cluster}) keepsin
		estadd local FE         "X"
		estadd local controls   "X"
		distinct eventid if e(sample)
		eststo col7, add(noevents r(ndistinct))

lab var ash_f1allpat        "All patents"
lab var ash_f1allpat_highq  "Top qual patents"
lab var ash_efficiency      "R\&D efficiency"
lab var f2logsale           "ln(sales)"
lab var f2logemp            "ln(employment)"
lab var f2TFP_KL            "TFP"
global coeflist1 = "trust_sd c.trust_sd#c.resqual"
global coeflist2 = "1.resqualpct#c.trust_sd 2.resqualpct#c.trust_sd 3.resqualpct#c.trust_sd 4.resqualpct#c.trust_sd 5.resqualpct#c.trust_sd"
esttab /*using "Table VI_Effect by pre-transition researcher-pool quality.tex"*/, ///
	cells(b(star fmt(3)) se(par fmt(3))) starlevels(* 0.1 ** 0.05 *** 0.01) ///
	collabels(none) label varwidth(33) modelwidth(12) ///
	mgroups("1-year" "2-year", pattern(1 0 0 0 1 0 0) ///
		prefix(\multicolumn{@span}{c}{) suffix(}) span) ///
	keep(${coeflist1} ${coeflist2}) order(${coeflist1} ${coeflist2}) ///	
	coeflab(trust_sd "CEO's trust" ///
			c.trust_sd#c.resqual "Trust $\times$ Researcher quality" ///
			1.resqualpct#c.trust_sd "Trust $\times$ Quality quintile 1" ///
			2.resqualpct#c.trust_sd "Trust $\times$ Quality quintile 2" ///
			3.resqualpct#c.trust_sd "Trust $\times$ Quality quintile 3" ///
			4.resqualpct#c.trust_sd "Trust $\times$ Quality quintile 4" ///
			5.resqualpct#c.trust_sd "Trust $\times$ Quality quintile 5") ///
	stats(FE controls N noevents, fmt(%9.0fc %9.0fc) ///
		lab("Event \& Year FEs" "Baseline controls" "Observations" "Events"))

cap log close

********************************************************************************
*           TABLE VII: CEO'S TRUST EFFECT IN BILATERAL TRUST SAMPLE            *
********************************************************************************
cap log close
log using "Table VII_Effect in bilateral trust sample.log", replace
	
//PREPARE DATA
use "Bilateral trust sample_nonUS.dta", clear
* construct additional variable
gen sameethnic = eubmcode == mainethcode & mainethshare >= 0.8
* set globals 
global firm = "firmage firmage2"
global ceo = "age age2 yrinco"
global bitrustFEs = "ceoid eubmcode boardid#year"
global bitrustsample = "eubmcode != 33 & haspat & year < 2012 & !nonUS" //eubmcode 33 = US
global cluster = "etheubmcode"
* set sample
qui reghdfe ash_f1allpatxc bitrust_sd logat logsale ${firm} ${ceo} if ${bitrustsample}, ///
	a(boardid eubmcode ceoid year) keepsin
gen bitrustsample = e(sample)


//PREPARE TABLE
eststo clear
eststo col1: /// baseline
	reghdfe ash_f1allpatxc bitrust_sd if bitrustsample, ///
	a(${bitrustFEs}) cluster(${cluster}) keepsin
		estadd local spec       "Baseline"
		estadd local FE_CEO     "X"
		estadd local FE_IC      "X"
		estadd local FE_FxY     "X"
		distinct boardid if e(sample)
		distinct brdeubmcode if e(sample)
		estadd scalar nofirmxcntrys = r(ndistinct)
		distinct boardid if e(sample)
		eststo col1, add(nofirms r(ndistinct))
eststo col2: /// additional fixed effects
	reghdfe ash_f1allpatxc bitrust_sd if bitrustsample, ///
	a(boardid#year ceoid#year eubmcode#year) cluster(${cluster}) keepsin
		estadd local spec       "Add FEs"
		estadd local FE_FxY     "X"
		estadd local FE_CEOxY   "X"
		estadd local FE_ICxY    "X"
		distinct brdeubmcode if e(sample)
		estadd scalar nofirmxcntrys = r(ndistinct)
		distinct boardid if e(sample)
		eststo col2, add(nofirms r(ndistinct))
eststo col3: /// additional fixed effects
	reghdfe ash_f1allpatxc bitrust_sd ${firm} ${ceo} if bitrustsample, ///
	a(ceoid boardid#eubmcode year) cluster(${cluster}) keepsin
		estadd local spec       "Add FEs"
		estadd local FE_CEO     "X"
		estadd local FE_FxIC    "X"
		estadd local FE_Y       "X"
		distinct brdeubmcode if e(sample)
		estadd scalar nofirmxcntrys = r(ndistinct)
		distinct boardid if e(sample)
		eststo col3, add(nofirms r(ndistinct))
eststo col4: /// forward citation-weighted
	reghdfe ash_f1allpatxc_citff bitrust_sd if bitrustsample, ///
	a(${bitrustFEs}) cluster(${cluster}) keepsin 
		estadd local spec       "Fwd cites"
		estadd local FE_CEO     "X"
		estadd local FE_IC      "X"
		estadd local FE_FxY     "X"
		distinct brdeubmcode if e(sample)
		estadd scalar nofirmxcntrys = r(ndistinct)
		distinct boardid if e(sample)
		eststo col4, add(nofirms r(ndistinct))
eststo col5: /// exclude same ethnicity
	reghdfe ash_f1allpatxc bitrust_sd if bitrustsample & !sameethnic, ///
	a(${bitrustFEs}) cluster(${cluster})
		estadd local spec       "Pair ctrls"
		estadd local exclsame   "X"
		estadd local FE_CEO     "X"
		estadd local FE_IC      "X"
		estadd local FE_FxY     "X"
		distinct brdeubmcode if e(sample)
		estadd scalar nofirmxcntrys = r(ndistinct)
		distinct boardid if e(sample)
		eststo col5, add(nofirms r(ndistinct))
eststo col6: /// common language control
	reghdfe ash_f1allpatxc bitrust_sd comlang_ethno if bitrustsample, ///
	a(${bitrustFEs}) cluster(${cluster}) keepsin
		estadd local spec       "Pair ctrls"
		estadd local FE_CEO     "X"
		estadd local FE_IC      "X"
		estadd local FE_FxY     "X"
		distinct brdeubmcode if e(sample)
		estadd scalar nofirmxcntrys = r(ndistinct)
		distinct boardid if e(sample)
		eststo col6, add(nofirms r(ndistinct))
eststo col7: /// geographical distance control
	reghdfe ash_f1allpatxc bitrust_sd distw if bitrustsample, ///
	a(${bitrustFEs}) cluster(${cluster}) keepsin
		estadd local spec       "Pair ctrls"
		estadd local FE_CEO     "X"
		estadd local FE_IC      "X"
		estadd local FE_FxY     "X"
		distinct brdeubmcode if e(sample)
		estadd scalar nofirmxcntrys = r(ndistinct)
		distinct boardid if e(sample)
		eststo col7, add(nofirms r(ndistinct))
eststo col8: /// genetic distance control
	reghdfe ash_f1allpatxc bitrust_sd fstdist_wt if bitrustsample, ///
	a(${bitrustFEs}) cluster(${cluster}) keepsin
		estadd local spec       "Pair ctrls"
		estadd local FE_CEO     "X"
		estadd local FE_IC      "X"
		estadd local FE_FxY     "X"
		distinct brdeubmcode if e(sample)
		estadd scalar nofirmxcntrys = r(ndistinct)
		distinct boardid if e(sample)
		eststo col8, add(nofirms r(ndistinct))

global coeflist = "bitrust_sd comlang_ethno distw fstdist_wt"
esttab /*using "Table VII_Effect in bilateral trust sample.tex"*/, ///
	cells(b(star fmt(3)) se(par fmt(3))) starlevels(* 0.1 ** 0.05 *** 0.01) ///
	nomtitle collabels(none) label varwidth(32) modelwidth(12) ///
	mgroups("arsinh(Future patent applications)", pattern(1 0 0 0 0 0 0 0) ///
		prefix(\multicolumn{@span}{c}{) suffix(}) span) ///
	keep(${coeflist}) order(${coeflist}) ///
	coeflab(bitrust_sd "CEO's bilateral trust" ///
			comlang_ethno "Common language dummy" ///
			distw "Geographical distance (1000km)" ///
			fstdist_wt "Genetic distance (z-score)") ///
	stats(spec FE_CEO FE_IC FE_FxY FE_CEOxY FE_ICxY FE_FxIC FE_Y exclsame N nofirmxcntrys nofirms, ///
		fmt(%9.0fc %9.0fc %9.0fc) ///
		lab("Specification" "CEO FEs" "Inventor country FEs" "Firm $\times$ Year FEs" "CEO $\times$ Year FEs" ///
			"Inv country $\times$ Year FEs" "Firm $\times$ Inv country's FEs" "Year FEs" ///
			"Excl same-country pairs" "Observations" "Firm $\times$ Inv country's" "Firms"))

cap log close

********************************************************************************
*           FIGURE I: DISTRIBUTION OF CEO'S INHERITED TRUST MEASURE            *
********************************************************************************

//PREPARE DATA
use "Baseline CEO firm year sample.dta", clear
* set globals
global firm = "firmage firmage2"
global ceo = "gender age age2 yrinco i.education"
global sample = "year < 2012 & !nonUS"
global cluster = "mainethcode"
* set sample
qui reghdfe ash_f1allpat trust_sd ${firm} ${ceo} if ${sample}, a(boardid year) keepsin
keep if e(sample)
keep ceoid trust
duplicates drop


//PREPARE FIGURE
sum trust, det
global trust_p1 = r(p1)
global trust_p10 = r(p10)
global trust_p50 = r(p50)
global trust_p90 = r(p90)
global trust_p99 = r(p99)

histogram trust if inrange(trust, ${trust_p1}, ${trust_p99}), ///
	width(0.008) color(navy) fintensity(inten80) lcolor(white) /// 
	xline(${trust_p10}, lpattern(shortdash) lcolor(cranberry) lwidth(medthin)) ///
	xline(${trust_p50}, lpattern(solid) lcolor(cranberry) lwidth(medthin)) ///
	xline(${trust_p90}, lpattern(shortdash) lcolor(cranberry) lwidth(medthin)) ///
	xtitle("CEO's inherited trust measure", size(medsmall)) ///
	xlabel(0.35(0.05)0.65, labsize(medsmall) nogrid) ///
	ytitle("Density", size(medsmall)) ///
	ylabel(0(5)20, labsize(medsmall) nogrid) ///
	graphregion(color(white) lwidth(vvvthick))
graph save "Fig I_CEO inherited trust distribution.gph", replace
graph export "Fig I_CEO inherited trust distribution.png", as(png) replace
graph export "Fig I_CEO inherited trust distribution.tif", as(tif) replace


********************************************************************************
*           FIGURE II: PRE-CHANGE PATENTS AND CHANGE IN CEO'S TRUST            *
********************************************************************************

//PREPATE DATA 
use "CEO transition event sample.dta", clear
* construct additional variables
gen yrbfchange_agg = min(abs(yrbfchange), 7)
* set globals
global firm = "firmage firmage2"
global ceo = "gender age age2 yrinco i.education"
global preeventsample = "!bothnonUS & yrbfchange != 0"
global cluster = "boardid"


//PREPARE FIGURE 
* FIGURE IIA: Common trends
reghdfe deltatrust c.ash_allpat#i.yrbfchange_agg trustbf logat ${firm} ${ceo} ///
	if ${preeventsample}, a(sic3#yrbfchange_agg year) cluster(${cluster})

foreach var in yr beta lower upper {
	cap drop `var'
	gen `var' = .
}
replace yr = _n
forval i = 1/7 {
	replace beta = _b[`i'.yrbfchange_agg#ash_allpat] if yr == `i'
	replace lower = _r_lb[`i'.yrbfchange_agg#ash_allpat] if yr == `i'
	replace upper = _r_ub[`i'.yrbfchange_agg#ash_allpat] if yr == `i'
}
replace yr = -yr

twoway ///
	(rcap lower upper yr, lcolor(gray) lwidth(medium)) ///
	(scatter beta yr, msymbol(circle) mcolor(navy) msize(medlarge)) ///
	if inrange(yr, -6, -1), ///
		yline(0, lpattern(solid) lcolor(cranberry) lwidth(medium)) ///
		xtitle("Year relative to CEO transition", size(medium)) ///
		xlabel(-6(1)-1, labsize(medium) nogrid) ///
		ytitle("Effect of arsinh(patents) on change in CEO's trust", size(medium)) ///
		ylabel(-0.06(0.02)0.06, labsize(medium) nogrid) ///
		legend(off) graphregion(color(white) lwidth(vvvthick))	
graph save "Fig IIA_Patent common trends.gph", replace
graph export "Fig IIA_Patent common trends.png", as(png) replace
graph export "Fig IIA_Patent common trends.tif", as(tif) replace


* FIGURE IIB: Pre-trend
reghdfe ash_allpat i.yrbfchange_agg ${firm} ${ceo} ///
	if ${preeventsample}, a(boardid year) cluster(${cluster})

foreach var in yr beta lower upper {
	cap drop `var'
	gen `var' = .
}	
replace yr = _n
forval i = 1/7 {
	replace beta = _b[`i'.yrbfchange_agg] if yr == `i'
	replace lower = _r_lb[`i'.yrbfchange_agg] if yr == `i'
	replace upper = _r_ub[`i'.yrbfchange_agg] if yr == `i'
}
replace yr = -yr

twoway ///
	(rcap lower upper yr, lcolor(gray) lwidth(medium)) ///
	(scatter beta yr, msymbol(circle) mcolor(navy) msize(medlarge)) ///
	if inrange(yr, -7, -2), ///
		yline(0, lpattern(solid) lcolor(cranberry) lwidth(thin)) ///
		xtitle("Year relative to CEO transition", size(medium)) ///
		xlabel(-7(1)-2, labsize(medium) nogrid) ///
		ytitle("Residual arsinh(patents)", size(medium)) ///
		ylabel(-0.3(0.1)0.3, labsize(medium) nogrid) ///
		legend(off) graphregion(color(white) lwidth(vvvthick))
graph save "Fig IIB_Patent pre trend.gph", replace
graph export "Fig IIB_Patent pre trend.png", as(png) replace
graph export "Fig IIB_Patent pre trend.tif", as(tif) replace


********************************************************************************
*                FIGURE IIIA: PATENTS BY CHANGE IN CEO'S TRUST                 *
********************************************************************************

//PREPARE DATA 
use "CEO transition event sample.dta", clear
* construct additional variables
gen yrwrtchange = year - changeyr
bysort eventid: egen haspre = max(yrwrtchange == -5)
bysort eventid: egen haspost = max(yrwrtchange == 4)
keep if haspre & haspost
drop if yrwrtchange == 0 & postchange == 1
* set globals
global firm = "logat firmage firmage2"
global ceo = "gender age age2 yrinco i.education"
global eventsample = "!bothnonUS"


//PREPARE FIGURE
cap drop FE_* respat
reghdfe ash_f1allpat ${firm} ${ceo} if ${eventsample}, a(FE_SIC = sic3 FE_YR = year) resid
predict respat, residual

keep if moretrust == 1 | lesstrust == 1
bysort yrwrtchange: egen tempmore = mean(respat) if moretrust == 1
bysort yrwrtchange: egen moretrustpat = mean(tempmore)
bysort yrwrtchange: egen templess = mean(respat) if lesstrust == 1
bysort yrwrtchange: egen lesstrustpat = mean(templess)
drop temp*

egen tempmore = mean(moretrustpat) if inrange(yrwrtchange, -5, -1) //equivalent to (-4, 0)
egen moretrustbase = mean(tempmore)
egen templess = mean(lesstrustpat) if inrange(yrwrtchange, -5, -1) //equivalent to (-4, 0)
egen lesstrustbase = mean(templess)
replace moretrustpat = moretrustpat - moretrustbase
replace lesstrustpat = lesstrustpat - lesstrustbase
drop temp*

replace yrwrtchange = yrwrtchange + 1
twoway ///
	(line moretrustpat yrwrtchange, lcolor(navy) lpattern(solid) lwidth(medium)) ///
	(line lesstrustpat yrwrtchange, lcolor(cranberry) lpattern(dash) lwidth(medium)) ///
	if inrange(yrwrtchange, -4, 5), ///
		xline(0, lpattern(solid) lcolor(gray) lwidth(medium)) ///
		xtitle("Year relative to CEO transition", size(medium)) ///
		xlabel(-4(1)5, labsize(medium) nogrid) ///
		ytitle("Residual arsinh(patents)", size(medium)) ///
		ylabel(-0.2(0.1)0.2, labsize(medium) nogrid) ///
		legend(off) graphregion(color(white) lwidth(vvvthick))
graph save "Fig IIIA_Patent evolution.gph", replace
graph export "Fig IIIA_Patent evolution.png", as(png) replace
graph export "Fig IIIA_Patent evolution.tif", as(tif) replace


********************************************************************************
*                FIGURE IIIB: EFFECTS OF CHANGE IN CEO'S TRUST                 *
********************************************************************************

//PREPARE DATA
use "CEO transition event sample.dta", clear
* construct additional variables
gen yrbfchange_agg = min(abs(yrbfchange), 7)
gen yrafchange_agg = min(abs(yrafchange), 7)
gen yrwrtchange = -yrbfchange_agg
replace yrwrtchange = yrafchange_agg if yrwrtchange == 0
replace yrwrtchange = yrwrtchange + 8
* set globals
global firm = "firmage firmage2"
global ceo = "gender age age2 yrinco i.education"
global eventsample = "!bothnonUS"
global cluster = "mainethcode"


//PREPARE FIGURE
reghdfe ash_allpat c.deltatrust##ib8.yrwrtchange ${firm} ${ceo} ///
	if ${eventsample}, a(eventid year) cluster(${cluster}) keepsin
	
foreach var in beta lower upper {
	cap drop `var'
	gen `var' = .
}
replace yrwrtchange = _n
forval i = 1/15 {
	replace beta = _b[`i'.yrwrtchange#deltatrust] if yrwrtchange == `i'
	replace lower = _r_lb[`i'.yrwrtchange#deltatrust] if yrwrtchange == `i'
	replace upper = _r_ub[`i'.yrwrtchange#deltatrust] if yrwrtchange == `i'
}
replace yrwrtchange = _n - 8

twoway ///
	(rcap lower upper yrwrtchange, lcolor(gray) lwidth(medium)) ///
	(scatter beta yrwrtchange, msymbol(circle) mcolor(navy) msize(medlarge)) ///
	if inrange(yrwrtchange, -4, 7), ///
		xline(0, lpattern(solid) lcolor(gray) lwidth(medium)) ///
		yline(0, lpattern(solid) lcolor(cranberry) lwidth(medium)) ///
		xtitle("Year relative to CEO transition", size(medium)) ///
		xlabel(-4(1)7, labsize(medium) nogrid) ///
		ytitle("Effect of change in CEO's trust on arsinh(patents)", size(medium)) ///
		ylabel(-0.1(0.05)0.25, labsize(medium) nogrid) ///
		legend(off) graphregion(color(white) lwidth(vvvthick))
graph save "Fig IIIB_Effect evolution.gph", replace
graph export "Fig IIIB_Effect evolution.png", as(png) replace
graph export "Fig IIIB_Effect evolution.tif", as(tif) replace


********************************************************************************
*     FIGURE IV: PROJECT QUALITY DISTRIBUTIONS UNDER DIFFERENT MECHANISMS      *
********************************************************************************

//PREPARE DATA
clear
set obs 1000
gen n = _n/(1000/8.5) //n ranges from 0 to 1.75
cap drop base dist_*
gen base = 0
gen dist_base = normalden(n, -1.5, 2.25)
gen dist_spread = normalden(n, -1.5, 3)
gen dist_meanshift = normalden(n, -0.75, 2.25)


//PREPARE FIGURE
* FIGURE IVA: Risk-taking mechanism
drarea (dist_base base dist_spread base n) if inrange(n, 0, 1.8), color(erose bluishgray)
graph addplot ///
	(function baseline = normalden(x,-1.5, 2.25), range(-11.5 8.5) ///
		lcolor(cranberry) lpattern(shortdash) lwidth(medium)) ///
	(function y = normalden(x,-1.5, 3), range(-11.5 8.5) ///
		lcolor(navy) lpattern(solid) lwidth(medium)), ///
		xline(-0.01, lpattern(solid) lcolor(cranberry) lwidth(medthin)) ///
		xline(1.81, lpattern(dash) lcolor(cranberry) lwidth(medthin)) ///
		xlabel(-0.01 "0" 1.81 "c", labsize(medsmall) notick) ///
		xtitle("") xscale(noline) ytitle("") yscale(noline) ylabel(none) ///
		legend(order(4 "Baseline distribution" 5 "High-risk distribution") size(medsmall) ///
			region(color(white) lwidth(vvvthick))) ///
		graphregion(color(white) lwidth(vvvthick))
graph save "Fig IVA_Risk taking mechanism illustration.gph", replace
graph export "Fig IVA_Risk taking mechanism illustration.png", as(png) replace
graph export "Fig IVA_Risk taking mechanism illustration.tif", as(tif) replace


* FIGURE IVB: Mean-shifting mechanism  
drarea (dist_base base dist_meanshift base n) if inrange(n, 0, 1.8), color(erose bluishgray)
graph addplot ///
	(function y = normalden(x,-1.5, 2.25), range(-11.5 8.5) ///
		lcolor(cranberry) lpattern(shortdash) lwidth(medium)) ///
	(function y = normalden(x,-0.75, 2.25), range(-11.5 8.5) ///
		lcolor(dkgreen) lpattern(solid) lwidth(medium)), ///
		xline(-0.01, lpattern(solid) lcolor(cranberry) lwidth(medthin))  ///
		xline(1.81, lpattern(dash) lcolor(cranberry) lwidth(medthin)) ///
		xlabel(-0.01 "0" 1.81 "c", labsize(medsmall) notick) ///
		xtitle("") xscale(noline) ytitle("") yscale(noline) ylabel(none) ///
		legend(order(4 "Baseline distribution" 5 "High-mean distribution") size(medsmall) ///
			region(color(white) lwidth(vvvthick))) ///
		graphregion(color(white) lwidth(vvvthick))
graph save "Fig IVB_Mean shifting mechanism illustration.gph", replace
graph export "Fig IVB_Mean shifting mechanism illustration.png", as(png) replace
graph export "Fig IVB_Mean shifting mechanism illustration.tif", as(tif) replace


********************************************************************************
*            FIGURE V: CEO'S TRUST EFFECT BY PATENT QUALITY DECILE             *
********************************************************************************

//PREPARE DATA
use "Baseline CEO firm year sample.dta", clear
* construct additional variables
gen tempsum = f1allpat_citff_dec1 + f1allpat_citff_dec2 + f1allpat_citff_dec3
forval i = 1/3 {
	replace f1allpat_citff_dec`i' = tempsum/3
}	
drop tempsum
* set globals
global firm = "firmage firmage2"
global ceo = "gender age age2 yrinco i.education"
global sample = "year < 2012 & !nonUS"
global cluster = "mainethcode"


//PREPARE FIGURE
* FIGURE VA: IHS patent counts
cap drop beta se lower upper q
foreach var in beta se lower upper {
	gen `var' = .
}
gen q = _n 
forval i = 1/10 {
	quietly {
		gen temppat = asinh(f1allpat_citff_dec`i')
		reghdfe temppat trust_sd ${firm} ${ceo} if ${sample}, ///
			a(boardid year) cluster(${cluster})
		replace beta = _b[trust_sd] if q == `i'
		replace se = _se[trust_sd] if q == `i'
		replace lower = _r_lb[trust_sd] if q == `i'
		replace upper = _r_ub[trust_sd] if q == `i'
		drop temppat
	}
}

twoway ///
	(line beta q, lcolor(navy) lpattern(shortdash) lwidth(medium)) ///
	(rcap lower upper q, lcolor(gray) lwidth(medium)) ///
	(scatter beta q, msymbol(circle) mcolor(navy) msize(medlarge)) ///
	if inrange(q, 1, 10), ///
		yline(0, lpattern(solid) lcolor(cranberry) lwidth(medium)) ///
		xtitle("Patent forward citation decile", size(medium)) ///
		xlabel(1(1)10, labsize(medium) nogrid) ///
		ytitle("Effect of CEO's trust on arsinh(patents)", size(medium)) ///
		ylabel(-0.02(0.02)0.08, labsize(medium) nogrid) ///
		legend(off) graphregion(color(white) lwidth(vvvthick))
graph save "Fig VA_Effect on log by quality decile.gph", replace
graph export "Fig VA_Effect on log by quality decile.png", as(png) replace
graph export "Fig VA_Effect on log by quality decile.tif", as(tif) replace


* FIGURE VB: Patent counts 	  
cap drop beta se lower upper q
foreach var in beta se lower upper {
	gen `var' = .
}
gen q = _n 
forval i = 1/10 {
	quietly {
		reghdfe f1allpat_citff_dec`i' trust_sd ${firm} ${ceo} if ${sample}, ///
			a(boardid year) cluster(${cluster})
		replace beta = _b[trust_sd] if q == `i'
		replace se = _se[trust_sd] if q == `i'
		replace lower = _r_lb[trust_sd] if q == `i'
		replace upper = _r_ub[trust_sd] if q == `i'
	}
}

twoway ///
	(line beta q, lcolor(navy) lpattern(shortdash) lwidth(medium)) ///
	(rcap lower upper q, lcolor(gray) lwidth(medium)) ///
	(scatter beta q, msymbol(circle) mcolor(navy) msize(medlarge)) ///
	if inrange(q, 1, 10), ///
		yline(0, lpattern(solid) lcolor(cranberry) lwidth(medium)) ///
		xtitle("Patent forward citation decile", size(medium)) ///
		xlabel(1(1)10, labsize(medium) nogrid) ///
		ytitle("Effect of CEO's trust on patent counts", size(medium)) ///
		ylabel(-1(1)3, labsize(medium) nogrid) ///
		legend(off) graphregion(color(white) lwidth(vvvthick))
graph save "Fig VB_Effect on level by quality decile.gph", replace
graph export "Fig VB_Effect on level by quality decile.png", as(png) replace
graph export "Fig VB_Effect on level by quality decile.tif", as(tif) replace